package com.dongdongshop.mq;

import com.alibaba.dubbo.config.annotation.Reference;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.dongdongshop.pojo.TbGoods;
import com.dongdongshop.pojo.TbGoodsDesc;
import com.dongdongshop.pojo.TbItem;
import com.dongdongshop.service.FreemarkerServeice;
import com.dongdongshop.service.GoodService;
import com.dongdongshop.service.GoodsEditService;
import com.dongdongshop.service.ItemService;

import freemarker.template.Configuration;
import freemarker.template.Template;
import org.apache.rocketmq.client.consumer.DefaultMQPushConsumer;
import org.apache.rocketmq.client.consumer.listener.ConsumeConcurrentlyContext;
import org.apache.rocketmq.client.consumer.listener.ConsumeConcurrentlyStatus;
import org.apache.rocketmq.client.consumer.listener.MessageListenerConcurrently;
import org.apache.rocketmq.common.message.MessageExt;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.apache.rocketmq.spring.core.RocketMQPushConsumerLifecycleListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer;

import java.io.FileWriter;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Component
@RocketMQMessageListener(topic = "my-topic",consumerGroup = "myGoodsId-group")
public class RocketMQItemPage implements RocketMQListener<String>, RocketMQPushConsumerLifecycleListener {

    @Autowired
    private FreemarkerServeice freemarkerServeice;

    @Override
    public void onMessage(String s) {

    }

    @Override
    public void prepareStart(DefaultMQPushConsumer defaultMQPushConsumer) {

        defaultMQPushConsumer.registerMessageListener(new MessageListenerConcurrently() {
            @Override
            public ConsumeConcurrentlyStatus consumeMessage(List<MessageExt> list, ConsumeConcurrentlyContext consumeConcurrentlyContext) {

                try {

                    for (MessageExt msg : list) {

                        byte[] body = msg.getBody();

                        String s = new String(body);

                        List<Long> l = (List<Long>) JSON.parse(s);

                        for (int i = 0; i < l.size(); i++) {

                            freemarkerServeice.createPage(l.get(i));
                        }

                    }
                }catch (Exception e) {

                    e.printStackTrace();

                    return ConsumeConcurrentlyStatus.RECONSUME_LATER;
                }

                return ConsumeConcurrentlyStatus.CONSUME_SUCCESS;

            }
        });
    }
}
